#!/bin/bash

# 构建脚本 - 用于编译和构建呼叫中心应用

set -e

echo "=== 开始构建呼叫中心应用 ==="

# 设置Go环境变量
export GO111MODULE=on
export GOPROXY=https://goproxy.cn,direct

# 创建输出目录
BUILD_DIR="./build"
mkdir -p $BUILD_DIR

# 清理旧的构建文件
echo "清理旧的构建文件..."
rm -rf $BUILD_DIR/*

# 安装依赖
echo "安装依赖..."
go mod download
go mod tidy

# 运行测试
echo "运行测试..."
go test ./... -v

# 构建应用
echo "构建应用..."

# 针对不同平台构建
BUILD_TARGETS=(
  "linux_amd64"
  "linux_arm64"
  "darwin_amd64"
  "darwin_arm64"
  "windows_amd64"
)

for target in "${BUILD_TARGETS[@]}"; do
  echo "构建目标: $target"
  
  # 解析目标平台
  OS="$(echo $target | cut -d'_' -f1)"
  ARCH="$(echo $target | cut -d'_' -f2)"
  
  # 设置环境变量
  export GOOS=$OS
  export GOARCH=$ARCH
  
  # 确定输出文件名
  OUTPUT_NAME="callcenter-api"
  if [ "$OS" = "windows" ]; then
    OUTPUT_NAME="callcenter-api.exe"
  fi
  
  # 执行构建
  echo "构建 $OS/$ARCH..."
  go build -ldflags "-w -s -X main.Version=1.0.0" -o "$BUILD_DIR/$target/$OUTPUT_NAME" ./cmd/api/main.go
  
  # 复制配置文件
  mkdir -p "$BUILD_DIR/$target/configs"
  cp .env.example "$BUILD_DIR/$target/.env.example"
  
  # 添加启动脚本
  if [ "$OS" = "windows" ]; then
    echo "@echo off
echo 启动呼叫中心API服务...
%~dp0$OUTPUT_NAME" > "$BUILD_DIR/$target/start.bat"
  else
    echo "#!/bin/bash
echo 启动呼叫中心API服务...
./$OUTPUT_NAME" > "$BUILD_DIR/$target/start.sh"
    chmod +x "$BUILD_DIR/$target/start.sh"
  fi
done

# 构建Docker镜像
echo "构建Docker镜像..."
docker build -t callcenter-api:1.0.0 .

# 打包结果
echo "打包构建结果..."
cd $BUILD_DIR
for target in "${BUILD_TARGETS[@]}"; do
  tar -czf "${target}.tar.gz" "$target"
done
cd -

echo "=== 构建完成 ==="
echo "构建结果位于: $BUILD_DIR/"